<template>
  <view class="container">
    <!-- 顶部标签页 -->
    <scroll-view
        class="tabs"
        scroll-x
        :scroll-left="scrollLeft"
    >
      <view
          v-for="(tab, index) in tabs"
          :key="index"
          class="tab-item"
          :class="{ active: currentTab === index }"
          @tap="switchTab(index)"
      >
        <text class="tab-text">{{ tab.name }}</text>
        <text class="badge" v-if="tab.count">{{ tab.count }}</text>
      </view>
    </scroll-view>

    <!-- 订单列表 -->
    <view class="order-list" v-if="currentTab !== 6">
      <scroll-view
          class="scroll-view"
          scroll-y
          @scrolltolower="loadMore()"
          refresher-enabled
          :refresher-triggered="refreshing"
          @refresherrefresh="onRefresh()"
      >
        <!-- 订单项 -->
        <view
            v-for="order in orderList"
            :key="order.id"
            class="order-item"
        >
          <!-- 订单头部 -->
          <view class="order-header">
            <view class="order-no-wrapper">
              <image
                  src="/static/profile/wodedingdan.png"
                  mode="aspectFit"
                  class="order-icon"
              />
              <text class="order-no selectable-text">订单号：{{ order.id }}</text>
            </view>
            <text class="order-status" :class="order.orderStatus">
              <image
                  v-if="order.orderStatus === 'pending'"
                  src="/static/profile/daifukuan.png"
                  mode="aspectFit"
                  class="status-icon"
              />
              <image
                  v-if="order.orderStatus === 'paid'"
                  src="/static/profile/daifahuo.png"
                  mode="aspectFit"
                  class="status-icon"
              />
              <image
                  v-if="order.orderStatus === 'shipped'"
                  src="/static/profile/yifahuo.png"
                  mode="aspectFit"
                  class="status-icon"
              />
              <image
                  v-if="order.orderStatus === 'completed'"
                  src="/static/profile/jiaoyiwancheng.png"
                  mode="aspectFit"
                  class="status-icon"
              />
              {{ getStatusText(order) }}
            </text>
          </view>

          <!-- 商品信息 -->
          <view
              class="product-info"
              @tap="goToOrderDetail(order.id)"
          >
            <image
                :src="order.productSKUVO?.image || '/static/https://fsp-1326500412.cos.ap-chengdu.myqcloud.com/default.png'"
                mode="aspectFill"
                class="product-image"
                @tap.stop="goToProductDetail(order.product?.id)"
            />
            <view class="product-detail">
              <text class="product-name selectable-text">{{ order.product?.name }}</text>
              <text class="sku-info selectable-text">{{ order.productSKUVO?.quantity }}</text>
              <view class="price-quantity">
                <text class="price">¥{{ order.productSKUVO?.price?.toFixed(2) }}</text>
                <text class="quantity">x{{ order.quantity }}</text>
              </view>
            </view>
          </view>

          <!-- 订单金额 -->
          <view class="order-amount">
            <text class="amount-label">实付金额</text>
            <text class="amount-value selectable-text">¥{{ order.totalPrice?.toFixed(2) }}</text>
          </view>

          <!-- 订单操作 -->
          <view class="order-actions">
            <button
                v-if="order.orderStatus === 'pending'"
                class="action-btn primary"
                @tap="payOrder(order)"
            >立即付款
            </button>
            <button
                v-if="order.orderStatus === 'shipped'"
                class="action-btn primary"
                @tap="confirmReceive(order)"
            >确认收货
            </button>
            <button
                v-if="order.orderStatus === 'pending'"
                class="action-btn secondary"
                @tap="cancelOrder(order)"
            >取消订单
            </button>
            <button
                v-if="order.orderStatus && ['paid', 'shipped', 'completed'].includes(order.orderStatus)"
                class="action-btn apply-service-btn"
                @tap="applyAfterSales(order)"
            >申请售后
            </button>
            <button
                v-if="order.orderStatus === 'completed' && !order.hasReview"
                class="action-btn review-btn"
                @tap="openReviewPopup(order)"
            >评价
            </button>
            <button
                v-if="order.orderStatus === 'completed' && order.hasReview"
                class="action-btn add-review-btn"
                @tap="openReviewPopup(order)"
            >追加评论
            </button>
          </view>
        </view>

        <!-- 空状态 -->
        <view class="empty-state" v-if="orderList.length === 0">
          <image src="/static/empty-order.png" mode="aspectFit" class="empty-icon"/>
          <text class="empty-title">暂无相关订单</text>
          <text class="empty-desc">您还没有相关订单记录</text>
          <button class="go-shopping-btn" @tap="goToHome">去逛逛</button>
        </view>

        <!-- 加载更多 -->
        <view class="loading-more" v-if="orderList.length > 0">
          {{ hasMore ? '加载中...' : '没有更多了' }}
        </view>
      </scroll-view>
    </view>

    <!-- 评价弹窗 -->
    <review-popup
        v-model:show="showReviewPopup"
        :order-id="currentOrderId"
        @success="onReviewSuccess"
    />

    <!-- 售后列表 -->
    <after-sales-list v-if="currentTab === 6" ref="afterSalesListRef"/>
  </view>
</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue';
import {onShow, onLoad as uniOnLoad} from '@dcloudio/uni-app';
import {
  cancelOrderUsingPost,
  confirmReceiptUsingPost,
  listMyOrderVoByPageUsingPost,
  payOrderUsingPost
} from '@/backend';
import type {API} from "@/backend/typings.d";
import AfterSalesList from '../afterSales/components/afterSalesList.vue';
import ReviewPopup from './components/review-popup.vue';

// 标签页配置
interface TabItem {
  name: string;
  status: string;
  count?: number;
}

const tabs = ref<TabItem[]>([
  {name: '全部', status: 'all'},
  {name: '待付款', status: 'pending'},
  {name: '待发货', status: 'paid'},
  {name: '待收货', status: 'shipped'},
  {name: '已完成', status: 'completed'},
  {name: '已取消', status: 'cancelled'},
  {name: '售后/退款', status: 'after_sales'}
]);

const currentTab = ref(0);
const scrollLeft = ref(0);
const orderList = ref<API.OrderVO[]>([]);
const pageNum = ref(1);
const pageSize = ref(10); // 首次加载10条
const loadMoreSize = ref(5); // 加载更多时5条
const hasMore = ref(true);
const refreshing = ref(false);

// 评价相关状态
const showReviewPopup = ref(false);
const currentOrderId = ref<number>();

// 新增售后相关数据
const afterSalesList = ref<API.AfterSalesServiceVO[]>([]);
const afterSalesPagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
});

const afterSalesListRef = ref<InstanceType<typeof AfterSalesList>>();

// 获取订单列表
const fetchOrders = async (refresh = false) => {
  if (refresh) {
    pageNum.value = 1;
    hasMore.value = true;
  }

  try {
    const currentTabData = tabs.value[currentTab.value];
    if (!currentTabData) {
      console.error('当前标签页数据不存在');
      uni.showToast({
        title: '获取订单列表失败',
        icon: 'none'
      });
      return;
    }

    const res = await listMyOrderVoByPageUsingPost({
      current: pageNum.value,
      pageSize: refresh ? pageSize.value : loadMoreSize.value,
      orderStatus: currentTabData.status === 'all' ? undefined : currentTabData.status,
      sortField: 'createTime',
      sortOrder: 'desc' // 按创建时间倒序，新订单在前
    });

    if (res.code === 0 && res.data) {
      const newRecords = res.data.records || [];
      if (refresh) {
        orderList.value = newRecords;
      } else {
        orderList.value = [...orderList.value, ...newRecords];
      }
      // 根据当前请求的 size 判断是否还有更多
      const currentSize = refresh ? pageSize.value : loadMoreSize.value;
      hasMore.value = newRecords.length === currentSize;
    }
  } catch (error) {
    console.error('获取订单列表失败：', error);
    uni.showToast({
      title: '获取订单列表失败',
      icon: 'none'
    });
  }
};

// 切换标签页
const switchTab = async (index: number) => {
  currentTab.value = index;
  if (index === 6) {
    // 售后标签页，刷新售后列表
    afterSalesListRef.value?.loadAfterSales();
  } else {
    orderList.value = [];
    await fetchOrders(true);
  }
};

// 获取状态文本
const getStatusText = (order: API.OrderVO) => {
  if (order.orderStatus === 'pending') {
    return '待支付';
  }
  if (order.orderStatus === 'paid') {
    return '待发货';
  }
  if (order.orderStatus === 'shipped') {
    return '待收货';
  }
  if (order.orderStatus === 'completed') {
    return '已完成';
  }
  if (order.orderStatus === 'cancelled') {
    return '已取消';
  }
  if (order.orderStatus === 'refunding') {
    return '退款处理中';
  }
  if (order.orderStatus === 'refunded') {
    return '已退款';
  }
  return '未知状态';
};

// 加载更多
const loadMore = () => {
  if (hasMore.value) {
    pageNum.value++;
    fetchOrders();
  }
};

// 下拉刷新
const onRefresh = async () => {
  refreshing.value = true;
  await fetchOrders(true);
  refreshing.value = false;
};

// 修改订单操作函数的类型
interface ModalResult {
  confirm: boolean;
  cancel?: boolean;
}

const payOrder = async (order: API.OrderVO) => {
  try {
    const result = await new Promise<ModalResult>((resolve) => {
      uni.showModal({
        title: '确认支付',
        content: `确定要支付￥${order.totalPrice?.toFixed(2)}吗？`,
        confirmText: '确定',
        cancelText: '取消',
        success: (res) => resolve(res),
        fail: () => resolve({confirm: false})
      });
    });

    if (!result.confirm) return;

    const res = await payOrderUsingPost(order.id!);
    if (res.code === 0) {
      await uni.showToast({
        title: '支付成功',
        icon: 'success'
      });
      await fetchOrders(true);
    } else {
      await uni.showToast({
        title: res.message || '支付失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('支付失败：', error);
    await uni.showToast({
      title: '支付失败',
      icon: 'none'
    });
  }
};

const confirmReceive = async (order: API.OrderVO) => {
  try {
    const result = await new Promise<ModalResult>((resolve) => {
      uni.showModal({
        title: '确认收货',
        content: '确认已收到商品吗？确认后无法撤销',
        confirmText: '确定',
        cancelText: '取消',
        success: (res) => resolve(res),
        fail: () => resolve({confirm: false})
      });
    });

    if (!result.confirm) return;

    const res = await confirmReceiptUsingPost(order.id!);
    if (res.code === 0) {
      await uni.showToast({
        title: '确认收货成功',
        icon: 'success'
      });
      await fetchOrders(true);
    } else {
      await uni.showToast({
        title: res.message || '确认收货失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('确认收货失败：', error);
    await uni.showToast({
      title: '操作失败',
      icon: 'none'
    });
  }
};

const cancelOrder = async (order: API.OrderVO) => {
  try {
    const result = await new Promise<ModalResult>((resolve) => {
      uni.showModal({
        title: '取消订单',
        content: '确定要取消该订单吗？',
        confirmText: '确定',
        cancelText: '取消',
        success: (res) => resolve(res),
        fail: () => resolve({confirm: false})
      });
    });

    if (!result.confirm) return;

    const res = await cancelOrderUsingPost(order.id!);
    if (res.code === 0) {
      await uni.showToast({
        title: '取消订单成功',
        icon: 'success'
      });
      await fetchOrders(true);
    } else {
      await uni.showToast({
        title: res.message || '取消订单失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('取消订单失败：', error);
    await uni.showToast({
      title: '操作失败',
      icon: 'none'
    });
  }
};

// 跳转到商品详情
const goToProductDetail = (productId?: number) => {
  if (productId) {
    uni.navigateTo({
      url: `/pages/product/detail?id=${productId}`
    });
  }
};

// 跳转到订单详情
const goToOrderDetail = (orderId?: number) => {
  if (orderId) {
    // 将订单id转为字符串并进行编码处理，防止Long型数值精度丢失
    const idStr = orderId.toString();
    uni.navigateTo({
      url: `/pages/order/detail?idStr=${encodeURIComponent(idStr)}`
    });
  }
};

// 检查登录状态
const checkLogin = () => {
  const token = uni.getStorageSync('token');
  if (!token) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/profile/profile'
      });
    }, 1500);
    return false;
  }
  return true;
};

// 打开评价弹窗
const openReviewPopup = (order: API.OrderVO) => {
  currentOrderId.value = order.id;
  showReviewPopup.value = true;
};

// 评价成功回调
const onReviewSuccess = () => {
  fetchOrders(true);
};

// 申请售后
const applyAfterSales = (order: API.OrderVO) => {
  uni.navigateTo({
    url: `/pages/afterSales/apply?order=${encodeURIComponent(JSON.stringify(order))}`
  });
};

// 跳转到首页
const goToHome = () => {
  uni.switchTab({
    url: '/pages/home/home'
  });
};

// 添加 onLoad 处理函数
uniOnLoad((options?: Record<string, any>) => {
  if (options?.tabIndex) {
    const index = parseInt(options.tabIndex);
    if (!isNaN(index) && index >= 0 && index < tabs.value.length) {
      switchTab(index);
    }
  }
});

onMounted(() => {
  if (checkLogin()) {
    fetchOrders(true);
  }
});

// 页面显示时刷新数据
onShow(() => {
  if (checkLogin()) {
    fetchOrders(true);
  }
});
</script>

<style scoped>
.container {
  height: 100vh;
  background: #f8f8f8;
  display: flex;
  flex-direction: column;
}

.tabs {
  background: #fff;
  white-space: nowrap;
  border-bottom: 2rpx solid #f5f5f5;
  flex-shrink: 0;
}

.tab-item {
  display: inline-block;
  padding: 24rpx 32rpx;
  position: relative;
}

.tab-text {
  font-size: 28rpx;
  color: #666;
}

.tab-item.active .tab-text {
  color: #ff5722;
  font-weight: 500;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 4rpx;
  background: #ff5722;
  border-radius: 2rpx;
}

.badge {
  position: absolute;
  top: 12rpx;
  right: 12rpx;
  min-width: 32rpx;
  height: 32rpx;
  padding: 0 8rpx;
  background: #ff5722;
  color: #fff;
  font-size: 20rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.order-list {
  flex: 1;
  overflow: hidden;
}

.scroll-view {
  height: 100%;
  padding: 20rpx;
  box-sizing: border-box;
}

.order-item {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.order-no-wrapper {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.order-icon {
  width: 32rpx;
  height: 32rpx;
}

.status-icon {
  width: 28rpx;
  height: 28rpx;
  margin-right: 4rpx;
  vertical-align: middle;
}

.order-no {
  font-size: 24rpx;
  color: #999;
}

.order-status {
  font-size: 26rpx;
  font-weight: 500;
}

.order-status.pending {
  color: #ff9800;
}

.order-status.paid,
.order-status.shipped {
  color: #2196f3;
}

.order-status.completed {
  color: #4caf50;
}

.order-status.cancelled,
.order-status.refunded {
  color: #999;
}

.product-info {
  display: flex;
  gap: 20rpx;
  padding: 20rpx 0;
  border-top: 2rpx solid #f5f5f5;
  border-bottom: 2rpx solid #f5f5f5;
}

.product-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  background: #f5f5f5;
}

.product-detail {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  line-height: 1.4;
}

.sku-info {
  font-size: 24rpx;
  color: #999;
  margin: 8rpx 0;
}

.price-quantity {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  font-size: 32rpx;
  color: #ff5722;
  font-weight: 600;
}

.quantity {
  font-size: 26rpx;
  color: #999;
}

.order-amount {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 12rpx;
  padding: 20rpx 0;
}

.amount-label {
  font-size: 26rpx;
  color: #666;
}

.amount-value {
  font-size: 32rpx;
  color: #ff5722;
  font-weight: 600;
}

.order-actions {
  display: flex;
  gap: 20rpx;
  justify-content: flex-end;
  padding-top: 20rpx;
  border-top: 1rpx solid #eee;
  margin-top: 20rpx;
}

.action-btn {
  min-width: 160rpx;
  height: 64rpx;
  font-size: 26rpx;
  border-radius: 32rpx;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 0 32rpx;
  transition: all 0.2s ease;
  position: relative;
  overflow: hidden;
  border: none;
  line-height: 1;
}

.action-btn::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: radial-gradient(circle, rgba(255,255,255,0.3) 10%, transparent 10.01%);
  transform: scale(10);
  opacity: 0;
  transition: transform 0.3s, opacity 0.5s;
}

.action-btn:active::after {
  transform: scale(0);
  opacity: 0.3;
  transition: 0s;
}

.primary {
  background: linear-gradient(135deg, #FF9800, #FF5722);
  color: #fff;
  box-shadow: 0 4rpx 16rpx rgba(255,87,34,0.25);
}

.primary:active {
  transform: translateY(2rpx);
  box-shadow: 0 2rpx 8rpx rgba(255,87,34,0.3);
}

.secondary {
  background: #fff;
  color: #666;
  border: 2rpx solid #ddd;
}

.apply-service-btn {
  background: linear-gradient(135deg, #42A5F5, #1976D2);
  color: #fff;
  box-shadow: 0 4rpx 16rpx rgba(33,150,243,0.25);
}

.apply-service-btn:active {
  transform: translateY(2rpx);
  box-shadow: 0 2rpx 8rpx rgba(33,150,243,0.3);
}

.review-btn {
  background: linear-gradient(135deg, #66BB6A, #388E3C);
  color: #fff;
  box-shadow: 0 4rpx 16rpx rgba(76,175,80,0.25);
}

.review-btn:active {
  transform: translateY(2rpx);
  box-shadow: 0 2rpx 8rpx rgba(76,175,80,0.3);
}

.add-review-btn {
  background: linear-gradient(135deg, #AB47BC, #7B1FA2);
  color: #fff;
  box-shadow: 0 4rpx 16rpx rgba(156,39,176,0.25);
}

.add-review-btn:active {
  transform: translateY(2rpx);
  box-shadow: 0 2rpx 8rpx rgba(156,39,176,0.3);
}

.action-btn:disabled {
  opacity: 0.7;
  filter: saturate(0.5);
  transform: none !important;
  box-shadow: none !important;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  background: #fff;
  border-radius: 16rpx;
  margin: 20rpx;
}

.empty-icon {
  width: 240rpx;
  height: 240rpx;
  margin-bottom: 40rpx;
}

.empty-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 16rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 40rpx;
}

.go-shopping-btn {
  width: 240rpx;
  height: 80rpx;
  background: linear-gradient(135deg, #ff9800, #ff5722);
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 16rpx rgba(255, 87, 34, 0.2);
}

.loading-more {
  text-align: center;
  padding: 30rpx;
  color: #999;
  font-size: 26rpx;
}

/* 售后服务样式 */
.after-sales-item {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
}

.service-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.service-no {
  font-size: 24rpx;
  color: #999;
}

.service-status {
  font-size: 26rpx;
  font-weight: 500;
}

.service-status.pending {
  color: #ff9800;
}

.service-status.processing {
  color: #2196f3;
}

.service-status.completed {
  color: #4caf50;
}

.service-status.rejected {
  color: #f44336;
}

.related-order {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.order-no {
  font-size: 24rpx;
  color: #666;
}

.service-type {
  font-size: 24rpx;
  color: #ff5722;
  background: #fff2ed;
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
}

.service-reason {
  margin-bottom: 16rpx;
}

.label {
  font-size: 26rpx;
  color: #666;
}

.content {
  font-size: 26rpx;
  color: #333;
}

.service-images {
  display: flex;
  gap: 16rpx;
  margin-bottom: 20rpx;
}

.evidence-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
}

.service-actions {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
}

.cancel-btn {
  color: #f44336;
  border-color: #f44336;
}

/* 添加可选中样式 */
.selectable-text {
  user-select: text;
  -webkit-user-select: text;
}
</style> 